package com.atguigu.lease.web.admin.controller.apartment;


import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.model.enums.ReleaseStatus;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


@Tag(name = "公寓信息管理")
@RestController
@RequestMapping("/admin/apartment")
public class ApartmentController {

    @Autowired
    private ApartmentInfoService apartmentInfoService;

    @Autowired
    private ApartmentFacilityService apartmentFacilityService ;

    @Autowired
    private ApartmentLabelService apartmentLabelService;

    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService ;

    @Autowired
    private GraphInfoService graphInfoService ;

    @Operation(summary = "保存或更新公寓信息")
    @PostMapping("saveOrUpdate")
    public Result saveOrUpdate(@RequestBody ApartmentSubmitVo apartmentSubmitVo) {

        /*
        Long apartmentId = apartmentSubmitVo.getId();
        //1. 删除旧关系
        if(apartmentId!=null){
            apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>().eq(ApartmentFacility::getApartmentId,apartmentId));
            apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>().eq(ApartmentLabel::getApartmentId,apartmentId));
            apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>().eq(ApartmentFeeValue::getApartmentId,apartmentId));
            graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemType,ItemType.APARTMENT).eq(GraphInfo::getItemId,apartmentId));

            //以下四行操作不对！
            //1-1 删除旧的配套关系
            //apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>().in(ApartmentFacility::getFacilityId, apartmentSubmitVo.getFacilityInfoIds()));
            //1-2 删除旧的标签关系
            //apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>().in(ApartmentLabel::getLabelId,apartmentSubmitVo.getLabelIds()));
            //1-3 删除旧的杂费值关系
            //apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>().in(ApartmentFeeValue::getFeeValueId,apartmentSubmitVo.getFeeValueIds()));
            //1-4 删除旧的图片关系
            //graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemType,ItemType.APARTMENT).eq(GraphInfo::getItemId,apartmentId));
        }

        //2. 保存公寓的基本信息
        apartmentInfoService.saveOrUpdate(apartmentSubmitVo);
        final Long apartmentId2 = apartmentSubmitVo.getId();

        //3.保存公寓配套信息
        //假设配套的id是：1、5、7、8
        //那么应该封装出四个ApartmentFacility对象
        apartmentSubmitVo.getFacilityInfoIds().stream().forEach(facilityInfoId -> {
            ApartmentFacility apartmentFacility = ApartmentFacility.builder().facilityId(facilityInfoId).apartmentId(apartmentId2).build();
            apartmentFacilityService.saveOrUpdate(apartmentFacility);
        });

        //4.保存公寓标签信息
        apartmentSubmitVo.getLabelIds().stream().forEach(labelId -> {
            apartmentLabelService.saveOrUpdate(ApartmentLabel.builder().labelId(labelId).apartmentId(apartmentId2).build());
        });

        //5.保存杂费值信息
        apartmentSubmitVo.getFeeValueIds().stream().forEach(feeValueId -> {
            apartmentFeeValueService.saveOrUpdate(ApartmentFeeValue.builder().apartmentId(apartmentId2).feeValueId(feeValueId).build());
        });

        //6.保存图片信息
        apartmentSubmitVo.getGraphVoList().forEach(graphVo -> {
            GraphInfo graphInfo = new GraphInfo();
            graphInfo.setName(graphVo.getName());
            graphInfo.setUrl(graphVo.getUrl());
            graphInfo.setItemType(ItemType.APARTMENT);
            graphInfo.setItemId(apartmentId2);
            graphInfoService.saveOrUpdate(graphInfo);
        });
        */

        //LoginUser loginUser = LoginUserContext.getLoginUser();
        //


        Long apartmentId = apartmentSubmitVo.getId();
        if(apartmentId!=null){
            graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemType,ItemType.APARTMENT).eq(GraphInfo::getItemId,apartmentId));
            apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>().eq(ApartmentFacility::getApartmentId,apartmentId));
            apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>().eq(ApartmentLabel::getApartmentId,apartmentId));
            apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>().eq(ApartmentFeeValue::getApartmentId,apartmentId));
        }

        apartmentInfoService.saveOrUpdate(apartmentSubmitVo);
        Long apartmentId2 = apartmentSubmitVo.getId();
        List<GraphInfo> graphInfoList = apartmentSubmitVo.getGraphVoList().stream().map(graphVo -> {
            GraphInfo graphInfo = new GraphInfo();
            //属性复制
            BeanUtils.copyProperties(graphVo, graphInfo);
            graphInfo.setItemId(apartmentId2);
            graphInfo.setItemType(ItemType.APARTMENT);
            return graphInfo;
        }).collect(Collectors.toList());
        graphInfoService.saveBatch(graphInfoList);

        apartmentFacilityService.saveBatch(apartmentSubmitVo.getFacilityInfoIds().stream().map(facilityInfoId ->
            ApartmentFacility.builder().facilityId(facilityInfoId).apartmentId(apartmentId2).build()
        ).collect(Collectors.toList()));

        apartmentLabelService.saveBatch(apartmentSubmitVo.getLabelIds().stream()
                .map(labelId -> ApartmentLabel.builder().apartmentId(apartmentId2).labelId(labelId).build()).collect(Collectors.toList()));

        apartmentFeeValueService.saveBatch(apartmentSubmitVo.getFeeValueIds().stream().map(feeValueId ->
            ApartmentFeeValue.builder().apartmentId(apartmentId2).feeValueId(feeValueId).build()
        ).collect(Collectors.toList()));

        return Result.ok();
    }

    @Operation(summary = "根据条件分页查询公寓列表")
    @GetMapping("pageItem")
    public Result<IPage<ApartmentItemVo>> pageItem(@RequestParam long current, @RequestParam long size, ApartmentQueryVo queryVo) {
        IPage page = Page.of(current,size);
        IPage<ApartmentItemVo> apartmentItemVoPage = apartmentInfoService.pageItem(page,queryVo);
        return Result.ok(apartmentItemVoPage);
    }

    @Operation(summary = "根据ID获取公寓详细信息")
    @GetMapping("getDetailById")
    public Result<ApartmentDetailVo> getDetailById(@RequestParam Long id) {

        /*
        //1. 查询公寓本身的信息
        ApartmentInfo apartmentInfo = apartmentInfoService.getById(id);

        //拷贝基本属性值
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        BeanUtils.copyProperties(apartmentInfo,apartmentDetailVo);

        Long apartmentId = apartmentInfo.getId();

        //2. 查询公寓的图片列表
        List<GraphInfo> graphInfoList = graphInfoService.list(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getItemId, apartmentId).eq(GraphInfo::getItemType, ItemType.APARTMENT));
        apartmentDetailVo.setGraphVoList(graphInfoList.stream().map(graphInfo -> GraphVo.builder().name(graphInfo.getName()).url(graphInfo.getUrl()).build()).collect(Collectors.toList()));

        //3. 查询公寓的配套信息列表
        // 不能使用这个语句查询配套列表：List<ApartmentFacility> list = apartmentFacilityService.list();
        // 1) 界面上需要展示 配套的名称
        // 2) ApartmentFacility这个类中没有配套名称
        // 3) ApartmentDetailVo中有一个成员： List<FacilityInfo>
        // 基于以上三点，我们需要 自定义 一个查询方法，用来根据公寓的id查询对应的 配套列表
        List<FacilityInfo> facilityInfoList = apartmentFacilityService.getFacilityInfoListByApartmentId(apartmentId);
        apartmentDetailVo.setFacilityInfoList(facilityInfoList);

        //4. 查询公寓的标签信息列表
        List<LabelInfo> labelInfoList = apartmentLabelService.getLabelInfoListByApartmentId(apartmentId);
        apartmentDetailVo.setLabelInfoList(labelInfoList);

        //5. 查询公寓的杂费值列表
        List<FeeValueVo> feeValueVoList = apartmentFeeValueService.getFeeValueListByApartmentId(apartmentId);
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);
        */
        ApartmentDetailVo apartmentDetailVo = apartmentInfoService.getApartmentDetailVoById(id);
        return Result.ok(apartmentDetailVo);
    }

    @Operation(summary = "根据id删除公寓信息")
    @DeleteMapping("removeById")
    public Result removeById(@RequestParam Long id) {
        apartmentInfoService.removeApartmentById(id);
        return Result.ok();
    }

    @Operation(summary = "根据id修改公寓发布状态")
    @PostMapping("updateReleaseStatusById")
    public Result updateReleaseStatusById(@RequestParam Long id, @RequestParam ReleaseStatus status) {
        apartmentInfoService.update(new LambdaUpdateWrapper<ApartmentInfo>()
                .eq(ApartmentInfo::getId, id)
                .set(ApartmentInfo::getIsRelease, status));
        return Result.ok();
    }

    @Operation(summary = "根据区县id查询公寓信息列表")
    @GetMapping("listInfoByDistrictId")
    public Result<List<ApartmentInfo>> listInfoByDistrictId(@RequestParam Long id) {
        return Result.ok(apartmentInfoService.list(new LambdaQueryWrapper<ApartmentInfo>().eq(ApartmentInfo::getDistrictId, id)));
    }
}














